<template>
  <div class="inline">
    <!-- 触发按钮 -->
    <el-button type="primary" @click="openDialog(false)">新增</el-button>
     
    <el-dialog
      v-model="visible"
      width="60%"
      class="dlg-fixed-footer"
      :title="creatingSystem ? '创建系统' : '系统/设备新增（一次创建多层设备）'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <!-- 顶部：起始父节点（仅系统层） + 创建系统按钮 -->

      <el-form-item class="mb12">
        <el-button
          class="ml12"
          :type="mode === 'device' ? 'primary' : 'default'"
          :plain="mode !== 'device'"
          @click="switchMode('device')"
        >
          创建母设备
        </el-button>
        <el-button
          class="ml12"
          :type="mode === 'system' ? 'primary' : 'default'"
          :plain="mode !== 'system'"
          @click="switchMode('system')"
        >
          创建系统
        </el-button>

        <el-button
          class="ml12"
          :type="mode === 'anyDevice' ? 'primary' : 'default'"
          :plain="mode !== 'anyDevice'"
          @click="switchMode('anyDevice')"
        >
          自由创建设备
        </el-button>

        <!-- 顶部说明：按当前模式展示 -->
        <div class="tip mt8" v-if="mode === 'device'">
          选择 “系统” 添加母设备。
        </div>
        <div class="tip mt8" v-else-if="mode === 'anyDevice'">
          从任意节点添加设备。
        </div>

        
      </el-form-item>

      <el-form
        v-if="mode === 'device' || mode === 'anyDevice'"
        :label-width="parentFormLabelWidth"
        class="mb12"
      >
        <el-form-item :label="parentLabel">
          <div class="flex-row">
            <el-cascader
              :key="cascaderKey"
              ref="cascaderRef"
              v-model="rootPath"
              :props="cProps"
              clearable
              filterable
              :placeholder="mode === 'device' ? '请选择系统' : '请选择父节点'"
              style="min-width: 360px"
              show-all-levels
              @change="onRootChange"
            >
              <template #default="{ node, data }">
                <div class="cas-opt">
                  <span class="cas-label" :title="data.label">{{
                    data.label
                  }}</span>
                  <el-tag
                    v-if="typeLabelOf(node, data)"
                    size="small"
                    :type="typeTagType(typeLabelOf(node, data))"
                    effect="light"
                    class="cas-badge"
                  >
                    {{ typeLabelOf(node, data) }}
                  </el-tag>
                </div>
              </template>
            </el-cascader>
          </div>
        </el-form-item>
      </el-form>

      <!-- 设备层卡片 -->
      <div class="cards">
        <el-card
          v-for="(item, i) in layers"
          :key="item.uid"
          shadow="hover"
          class="layer-card"
        >
        <template #header>
            <div class="card-head">
              <div class="title">
                
                <el-tag size="small" type="primary" effect="plain">
                  {{ typeName(item.nodeType) }}
                </el-tag>
                
                <span class="path-preview">{{ pathPreview(i) }}</span>
              </div>
              <div class="ops" v-if="!creatingSystem">
                
                <el-button
                  link
                  size="small"
                  type="danger"
                  :disabled="layers.length === 1"
                  @click="remove(i)"
                  >删除</el-button
                >
              </div>
            </div>
          </template>
          <!-- ✅ 分支：系统层显示精简表单 -->
          <template v-if="creatingSystem && item.nodeType === 'SYSTEM'">
            <el-form :model="item" label-width="90px" class="layer-form">
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="系统编码" prop="code">
                    <el-input
                      v-model="item.code"
                      placeholder="请输入系统编码"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="系统名称" prop="name">
                    <el-input
                      v-model="item.name"
                      placeholder="请输入系统名称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否关键" prop="isKey">
                    <el-select v-model="item.isKey" placeholder="请选择">
                      <el-option label="非关键系统" :value="0" />
                      <el-option label="关键系统" :value="1" />                      
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template>

          <!-- ✅ 否则：显示原先复杂设备表单 -->
          <template v-else>
            <el-form
              :model="item"
              :rules="rulesFor(i)"
              :ref="setFormRef(i)"
              label-width="92px"
              class="layer-form"
            >
              <el-row :gutter="12">
                <el-col :span="8">
                  <!-- 唯一的“设备类型”表单项 -->
                  <el-form-item label="类型" prop="nodeType">
                    <el-select-v2
                      v-model="item.nodeType"
                      :options="typeOptionsFor(i)"
                      :disabled="creatingSystem"
                      placeholder="请选择类型"
                      clearable
                      filterable
                      @change="onTypeChange(i)"
                    />
                  </el-form-item>
                </el-col>

                <!-- <el-col :span="8">
                  <el-form-item :label="labelOf('code', item)" prop="code">
                    <el-input
                      v-model="item.code"
                      placeholder="设备编码（唯一，必填, 大写字母）"
                      @input="onCodeInput(item, $event)"
                      inputmode="latin"
                      @blur="checkBeTypeFirstData(item.code, item)"
                    />
                  </el-form-item>
                </el-col> -->
                <el-col :span="8">
                  <el-form-item :label="labelOf('name', item)" prop="name">
                    <el-input v-model="item.name" placeholder="请输入名称" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="归属部门" prop="deptId">
                    <el-tree-select
                      v-model="item.deptId"
                      :data="deptOptions"
                      filterable
                      clearable
                      :props="{
                        value: 'id',
                        label: 'label',
                        children: 'children',
                      }"
                      value-key="id"
                      placeholder="请选择归属部门"
                      check-strictly
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设备类别">
                    <el-input
                      v-model="item.beType"
                      placeholder=""
                      @input="onBeTypeInput(item, $event)"
                      @blur="checkBeTypeFirstData(item.beType, item)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设备模块">
                    <el-input v-model="item.mokuai" placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="设备区域">
                    <el-input v-model="item.area" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设备规格">
                    <el-input v-model="item.specification" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设备材质">
                    <el-input v-model="item.material" placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="设备单位">
                    <el-input v-model="item.unit" placeholder="例：台" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设备数量">
                    <el-input v-model="item.quantity" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设备金额">
                    <el-input
                      v-model="item.amount"
                      placeholder="填数值即可 (单位:万 )"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="设计温度">
                    <el-input
                      v-model="item.designTemp"
                      placeholder="(单位:℃ )"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设计压力">
                    <el-input
                      v-model="item.designPress"
                      placeholder="(单位:MPa )"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="电机功率">
                    <el-input
                      v-model="item.motorPower"
                      placeholder="填数值即可 (单位:KW )"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="搅拌形式">
                    <el-input v-model="item.mixingType" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="特种设备">
                    <el-select
                      v-model.number="item.isSpecial"
                      placeholder="请选择类型"
                    >
                      <el-option label="是" :value="1" />
                      <el-option label="否" :value="0" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设备状态" prop="status">
                    <el-select
                      v-model.number="item.status"
                      placeholder="请选择设备状态"
                    >
                      <el-option
                        v-for="dict in asset_node_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="Number(dict.value)"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="设备型号">
                    <el-input v-model="item.model" placeholder="" />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="设备品牌">
                    <el-input v-model="item.brand" placeholder="" />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="制造厂家">
                    <el-input v-model="item.manufacturer" placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form :model="systemInfo" label-width="90px" class="layer-form">
                <el-row :gutter="12">
                  <el-col :span="8">
                    <el-form-item label="系统编码">
                      <el-input v-model="systemInfo.code" placeholder="请输入系统编码" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="系统名称">
                      <el-input v-model="systemInfo.name" placeholder="请输入系统名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="是否关键">
                      <el-select v-model="systemInfo.isKey" placeholder="请选择">
                        <el-option label="关键系统" :value="1" />
                        <el-option label="非关键系统" :value="0" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>

              <el-form-item label="备注说明">
                <el-input
                  v-model="item.remark"
                  placeholder="可空"
                  type="textarea"
                  :rows="2"
                />
              </el-form-item>

              <div class="layer-footer">
    <el-button
      size="small"
      type="primary"
      plain
      @click="openNextLayer(item)"
    >
      ＋ 新增下一级（{{ nextTypeLabel(item.nodeType) }}）
    </el-button>

    <!-- 每个层级自己的弹窗 -->
    <DeviceLayerTable
      :ref="(el) => { if (el) layerDialogRefs[item.uid] = el }"
      @confirm="(rows) => handleNextLayerConfirm(item, rows)"
    />
  </div>
      

        
            </el-form>
          </template>

          <template v-for="child in item.children" :key="child.uid">
  <el-card class="child-card" shadow="never">
    <div class="child-title">
      <el-tag type="info" size="small">{{ TYPE_LABELS[child.nodeType] }}</el-tag>
      <span>{{ child.name || '未命名' }}</span>
    </div>
  </el-card>
</template>



        </el-card>
      </div>

      <!-- 新增一层：创建系统模式隐藏 -->
      <!-- <div class="add-area" v-if="!creatingSystem && layers.length">
        <el-button @click="addTail">＋ 新增一层</el-button>
      </div> -->
      <!-- 新增一层：创建系统模式隐藏 + 若最后层为子设备隐藏 -->
      <div
        class="add-area"
        v-if="!creatingSystem && layers.length && lastLayerType !== 'MODULE'"
      >
        <el-button @click="addTail">＋ 新增一层</el-button>
      </div>

      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submit"
          >创建</el-button
        >
      </template>

      <!-- 嵌入 AddSpareDialog 组件 -->
      <AddSpareDialog ref="addDialog" @confirm="onAddSpareConfirm" />
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  computed,
  onMounted,
  getCurrentInstance,
  nextTick,
} from "vue"; // ← ✅ nextTick
import { ElMessage } from "element-plus";
import { cascaderChildren, createRoute } from "@/api/sbtz/sbtz";
import { loadAllParams } from "@/api/page";
import {
  listSpares,
  listSpare,
  getVendorsBySpare,
  getSpecsBySpareVendor,
} from "@/api/sbtz/spare";
import { listSbtype } from "@/api/sbtz/sbtype";
import { deptTreeSelect } from "@/api/system/user";

import { checkBeTypeFirst } from "@/api/sbtz/sbtz"; // 你需要新建此接口
import AddSpareDialog from "@/components/sbtz/spare/AddSpareDialog.vue";
// 存储每个层的弹窗引用
const layerDialogRefs = reactive({});

const systemInfo = reactive({
  code: "",
  name: "",
  isKey: null,
});
const { proxy } = getCurrentInstance();
const { asset_node_status } = proxy.useDict("asset_node_status");

const visible = ref(false);
const loading = ref(false);
const creatingSystem = ref(false); // true=创建系统；false=在系统下新增链路
const cascaderKey = ref(0);
const cascaderRef = ref(null);
const showAllNodes = ref(false);
const selectedParentType = ref(null);
const parentLabel = ref("系统");
const mode = ref("device");

const addDialog = ref(null);
const currentLayerIndex = ref(null);
const lastLayerType = computed(() => {
  if (!layers.length) return null;
  return layers[layers.length - 1].nodeType;
});

// script setup 里加
const LABELS_SYS = {
  nodeType: "系统类型",
  code: "系统编码",
  name: "系统名称",
  deptId: "归属部门",
  status: "系统状态",
  remark: "系统备注",
  beType: "系统类别",
  mokuai: "系统模块",
  area: "系统区域",
  specification: "系统规格",
  material: "系统材质",
  unit: "系统单位",
  quantity: "系统数量",
  amount: "系统金额",
  model: "系统型号",
  brand: "系统品牌",
  manufacturer: "制造厂家",
  designTemp: "设计温度",
  designPress: "设计压力",
  motorPower: "电机功率",
  mixingType: "搅拌形式",
};
const LABELS_DEV = {
  nodeType: "设备类型",
  code: "设备编码",
  name: "设备名称",
  deptId: "归属部门",
  status: "设备状态",
  remark: "备注说明",
  beType: "设备类别",
  mokuai: "设备模块",
  area: "设备区域",
  specification: "设备规格",
  material: "设备材质",
  unit: "设备单位",
  quantity: "设备数量",
  amount: "设备金额",
  model: "设备型号",
  brand: "设备品牌",
  manufacturer: "制造厂家",
  designTemp: "设计温度",
  designPress: "设计压力",
  motorPower: "电机功率",
  mixingType: "搅拌形式",
};
// 当前表单项用系统文案的条件：该层就是 SYSTEM（或创建系统模式下的唯一层）
const isSystemLayer = (item) =>
  item?.nodeType === "SYSTEM" || (creatingSystem.value && layers.length === 1);
const labelOf = (field, item) =>
  (isSystemLayer(item) ? LABELS_SYS[field] : LABELS_DEV[field]) || field;

// 顶部“父节点选择”这行的 label 宽度：device=90px，anyDevice=160px，其它(系统)为0避免占位
const parentFormLabelWidth = computed(() => {
  if (mode.value === "device") return "60px";
  if (mode.value === "anyDevice") return "160px";
  return "0px"; // 'system' 时这块本就不显示，给0更稳妥
});

import DeviceLayerTable from "@/components/sbtz/node/DeviceLayerTable.vue";

const currentType = ref("MACHINE"); // 父级传递的设备类型
const layerRows = ref([]); 
const layerDialogRef = ref(null); // 弹窗引用
const currentParentItem = ref(null);
function onTableUpdate(newRows) {
  console.log("✅ 子组件更新:", newRows);
  layerRows.value = newRows;
}

function onBeTypeInput(item, val) {
  const inputEl = event?.target || document.activeElement;
  const raw = val || "";
  const filtered = raw.toUpperCase().replace(/[^A-Z0-9_-]/g, "");
  item.beType = filtered;

  if (inputEl) {
    const start = inputEl.selectionStart;
    const end = inputEl.selectionEnd;
    requestAnimationFrame(() => {
      try {
        inputEl.setSelectionRange(start, end);
      } catch {}
    });
  }

  // ✅ 输入时实时检测
  checkBeTypeFirstData(item.beType, item);
}



// ✅ 根据 nodeType 计算下一层类型
function nextType(currentType) {
  const idx = ORDER.indexOf(currentType);
  if (idx === -1 || idx === ORDER.length - 1) return null;
  return ORDER[idx + 1];
}

 

// ✅ 主逻辑：在当前卡片之后新增一层
function addNextLayer(item) {
  const currentIndex = layers.findIndex((x) => x.uid === item.uid);
  if (currentIndex === -1) return;

  const next = nextType(item.nodeType);
  if (!next) {
    return ElMessage.warning("已达到最底层，无法再新增下一级。");
  }

  // ✅ 在当前卡片下方插入新层
  layers.splice(currentIndex + 1, 0, makeEmptyLayer(next));

  ElMessage.success(`已新增 ${TYPE_LABELS[next]} 层`);
}

 

// ✅ 打开下一级弹窗
// 打开对应层的弹窗
async function openNextLayer(item) {
  await nextTick();
  const dialog = layerDialogRefs[item.uid];
  if (!dialog) return ElMessage.error("未找到该层的弹窗实例");
  dialog.open(item);
}

// ✅ 计算下一层类型
function getNextType(type) {
  const idx = ORDER.indexOf(type);
  return idx === -1 || idx === ORDER.length - 1 ? null : ORDER[idx + 1];
}

function handleConfirm(rows) {
  console.log("✅ 新增的子层数据：", rows);
  ElMessage.success("已新增下一级");
}

// function nextTypeLabel(type) {
//   const map = {
//     SYSTEM: "母设备",
//     MACHINE: "子设备",
//     MODULE: "部件",
//     COMPONENT: "零件",
//   };
//   return map[type] || "下一级";
// }

function nextTypeLabel(type) {
  const next = getNextType(type);
  return TYPE_LABELS[next] || "下一级";
}

async function checkBeTypeFirstData(beType, item) {
  // 如果是 code 调用过来的（即 beType 其实是 code）
  if (beType && beType.includes("-")) {
    const prefix = beType.split("-")[0];
    beType = prefix;
  }
  item.beType = beType;
  if (!beType) {
    item.showAddSpare = false; // ✅ 仅改当前卡片
    return;
  }

  try {
    const res = await checkBeTypeFirst({ beType });
    console.log(res);

    // 注意这里要取 res.data.exists
    const exists = res?.data?.exists === true;

    // 如果 exists 为 true，则不显示“自定义备件”按钮
    item.showAddSpare = !exists;
  } catch {
    item.showAddSpare = false;
  }
}

function openAddSpare(i) {
  currentLayerIndex.value = i;
  nextTick(() => {
    addDialog.value?.open?.();
  });
}

function onAddSpareConfirm(spareList) {
  const layer = layers[currentLayerIndex.value];
  if (!layer) return;

  console.log(spareList);
  layer.spareCustom = JSON.parse(JSON.stringify(spareList));
}

// 起始父节点（仅系统层）
const rootPath = ref([]); // 只允许长度=1
const selectedParentId = computed(() => {
  if (Array.isArray(rootPath.value) && rootPath.value.length) {
    // 设备模式取系统（第一个）；任意设备模式取最后一个节点
    return mode.value === "device"
      ? rootPath.value[0]
      : rootPath.value[rootPath.value.length - 1];
  }
  return 0;
});

// ✅ 新增：控制强制刷新

function refreshCascader() {
  // ✅ 新增：刷新起始父节点选择框数据
  // rootPath.value = [];               // 清空当前选择（可保留也行，看需求）
  cascaderKey.value += 1; // 变更 key，强制组件重建，触发懒加载
}

function hideAllCards() {
  layers.splice(0, layers.length);
}

async function focusCascader() {
  await nextTick();
  // 优先用组件的 focus（若支持），否则退回到原生 input
  if (cascaderRef.value?.focus) {
    cascaderRef.value.focus();
  } else {
    cascaderRef.value?.$el?.querySelector?.("input")?.focus();
  }
}

// 新增一条备件组
function addSpareRelation(layerIndex) {
  const layer = layers[layerIndex];
  layer.spareRelations.push({
    uid: Math.random().toString(36).slice(2),
    spareId: null,
    vendor: null,
    spec: null,
    vendorOptions: [],
    specOptions: [],
  });
}

function toggleShowAllNodes() {
  showAllNodes.value = !showAllNodes.value;

  // ✅ 同步更新标题文字
  parentLabel.value = showAllNodes.value ? "自定义设备层级节点" : "系统";

  refreshCascader();
  hideAllCards();
  // ElMessage.info(
  //   showAllNodes.value
  //     ? "自定义设备层级节点模式已开启，可选择任意节点"
  //     : "已切回仅系统层模式"
  // );
}

// 删除一条备件组
function removeSpareRelation(layerIndex, relationIndex) {
  layers[layerIndex].spareRelations.splice(relationIndex, 1);
}

// 复制一条备件组
function copySpareRelation(layerIndex, relationIndex) {
  const src = layers[layerIndex].spareRelations[relationIndex];
  layers[layerIndex].spareRelations.splice(relationIndex + 1, 0, {
    ...JSON.parse(JSON.stringify(src)),
    uid: Math.random().toString(36).slice(2),
  });
}

// 当选择备件变化时 -> 更新厂商
async function onSpareChange(layerIndex, relationIndex) {
  const sr = layers[layerIndex].spareRelations[relationIndex];
  sr.vendor = null;
  sr.spec = null;
  sr.specOptions = [];
  sr.vendorOptions = [];
  if (sr.spareId) sr.vendorOptions = await getVendorsBySpare(sr.spareId);
}

// 当选择厂商变化时 -> 更新规格
async function onVendorChange(layerIndex, relationIndex) {
  const sr = layers[layerIndex].spareRelations[relationIndex];
  sr.spec = null;
  sr.specOptions = [];
  if (sr.spareId && sr.vendor)
    sr.specOptions = await getSpecsBySpareVendor(sr.spareId, sr.vendor);
}

// 层级顺序常量
// ✅ 类型顺序常量（已有则保留）
const ORDER = ["SYSTEM", "MACHINE", "MODULE", "COMPONENT", "PART"];
const TYPE_LABELS = {
  SYSTEM: "系统",
  MACHINE: "母设备",
  MODULE: "子设备",
  COMPONENT: "部件",
  PART: "零件",
};

// 估算层级（父路径长度 + 当前层序号）
const baseLevel = ref(0);
watch(rootPath, () => {
  baseLevel.value = creatingSystem.value ? 0 : rootPath.value?.length || 0;
});

function typeLabel(type) {
  return TYPE_LABELS[type] || "-";
}
 

// 每层独立处理确认
function handleNextLayerConfirm(parent, newRows) {
  if (!Array.isArray(newRows) || newRows.length === 0)
    return ElMessage.warning("未接收到有效数据");

  // 🔹 保证 parent 有独立 children 数组
  if (!Array.isArray(parent.children)) {
    parent.children = [];
  }

  // 🔹 获取下一级类型
  const nextType = getNextType(parent.nodeType);
  if (!nextType) return ElMessage.warning("已是最底层");

  // 🔹 每次点击确认时，先清空旧 children（模拟重新填写）
  parent.children.splice(0, parent.children.length);

  // 🔹 再把新数据映射进去
  newRows.forEach((r) => {
    parent.children.push({
      ...makeEmptyLayer(nextType), // 默认结构
      ...r,                        // 用户输入数据
      nodeType: nextType,
      parentUid: parent.uid,       // 标记所属父级
    });
  });

  console.log(`✅ [${parent.name}] 的下一级已更新:`, parent.children);
  ElMessage.success(`已为「${parent.name}」新增 ${TYPE_LABELS[nextType]} 层`);
}



// 只显示系统层：根请求返回系统列表，强制 leaf=true
function typeLabelOf(node, data) {
  const code = data && (data.nodeType || data.node_type);
  if (code && TYPE_LABELS[code]) return TYPE_LABELS[code];
  return null;
}
function typeTagType(label) {
  const map = {
    系统: "success",
    母设备: "primary",
    子设备: "warning",
    部件: "warning",
    零件: "info",
  };
  return map[label] || "info";
}
function typeName(code) {
  return TYPE_LABELS[code] || code || "未知";
}

// 懒加载：device=仅系统; anyDevice=全部
const cProps = {
  checkStrictly: true,
  emitPath: true,
  value: "id",
  label: "label",
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const parentId = node.level === 0 ? 0 : node.value;

    try {
      const res = await cascaderChildren(parentId);
      let list = res?.data || [];

      // ✅ 情况1：创建母设备模式 → 仅显示系统层
      if (mode.value === "device" && node.level === 0) {
        list = list
          .filter((x) => (x.nodeType || x.node_type) === "SYSTEM")
          .map((x) => ({ ...x, leaf: true }));
      }

      // ✅ 情况2：自由创建设备模式 → 在母设备层级终止懒加载
      if (mode.value === "anyDevice") {
        list = list.map((x) => {
          const type = x.nodeType || x.node_type;
          // 若为母设备，则不再允许下钻（leaf=true）
          if (type === "MACHINE") {
            return { ...x, leaf: true };
          }
          return x;
        });
      }

      resolve(list);
    } catch {
      resolve([]);
    }
  },
};

 

// 只保留“当前层及以下”的类型（把上层类型从当前层可选项中移除）
// 第 i 层允许的类型：ORDER.slice(1 + i)
function allowedTypeCodesForIndex(i) {
  if (creatingSystem.value) return ["SYSTEM"];
  const start = Math.min(1 + i, ORDER.length - 1); // 0层→从1开始(去掉SYSTEM)，1层→从2开始...
  return ORDER.slice(start);
}

// 供下拉使用的 options（结合后端字典）
const typeOptions = ref([]);
function typeOptionsFor(i) {
  // 创建系统模式：只显示 SYSTEM
  if (creatingSystem.value) {
    return [{ value: "SYSTEM", label: "系统" }];
  }

  // ✅ 仅保留母设备(MACHINE) 和 子设备(MODULE)
  const options = [
    { value: "MACHINE", label: "母设备" },
    { value: "MODULE", label: "子设备" },
  ];

  // ✅ 第一个设备层：可选母设备或子设备
  if (i === 0) return options;

  // ✅ 其他层：只允许子设备
  return [options[1]];
}

// 字典与数据
const spareListOptions = ref([]);
const deptOptions = ref(undefined);
const deptMap = new Map();

function buildDeptTree(nodes = []) {
  return nodes.map((n) => {
    const children = buildDeptTree(n.children || []);
    const node = {
      ...n,
      children,
      // 规则：有 children 的视为目录/公司层，禁用选择；叶子可选
      disabled: children.length > 0,
    };
    deptMap.set(n.id, node);
    return node;
  });
}

function isLeafDeptId(id) {
  const node = deptMap.get(id);
  return !!node && (!node.children || node.children.length === 0);
}

function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptMap.clear();
    deptOptions.value = buildDeptTree(response.data || []);
  });
}

async function getTypeList() {
  const res = await listSbtype(loadAllParams);
  typeOptions.value = (res?.rows ?? []).map(
    ({ typeCode: value, displayName: label }) => ({ value, label })
  );
}
async function getSpareList() {
  // 你也可直接用 listSpares；这里沿用 listSpare 以匹配你现有 API
  const res = await listSpare(loadAllParams);
  spareListOptions.value = (res?.rows ?? []).map(
    ({ id: value, name: label }) => ({ value, label })
  );
}

onMounted(() => {
  getTypeList();
  getSpareList();
  getDeptTree();
});

// 层数据 + 规则
function makeEmptyLayer(type = "MACHINE") {
  return {
    uid: Math.random().toString(36).slice(2),
    nodeType: type,
    name: "",
    code: "", 
    stockTotal: 0,
    stockAvailable: 0,
    remark: "",
    specification: "",
    model: "",
    material: "",
    power: "",
    brand: "",
    manufacturer: "",
    isSpecial: null,
    deptId: null,
    status: 0,
    spareIds: [],
    spareRelations: [
      {
        uid: Math.random().toString(36).slice(2),
        spareId: null,
        vendor: null,
        spec: null,
        status: 1,
        vendorOptions: [],
        specOptions: [],
      },
    ],

    // 新增字段
    mokuai: null,
    area: null,
    designTemp: null,
    designPress: null,
    motorPower: null,
    mixingType: null,
    beType: null,
    unit: null,
    quantity: null,
    amount: null,
    showAddSpare: false, // ✅ 新增：每层独立控制自定义备件显示 
  };
}
const layers = reactive([]);
const formRefs = [];
const setFormRef = (i) => (el) => {
  formRefs[i] = el;
};

function onCodeInput(item, val) {
  const inputEl = event?.target || event?.srcElement || document.activeElement;
  if (!inputEl) {
    // 容错
    const s = (val || "").toUpperCase().replace(/[^A-Z0-9\-_]/g, "");
    if (s !== item.code) item.code = s;
    return;
  }

  // 记录光标位置
  const start = inputEl.selectionStart;
  const end = inputEl.selectionEnd;

  // 转换值
  const raw = val || "";
  const filtered = raw.toUpperCase().replace(/[^A-Z0-9\-_]/g, "");
  item.code = filtered;

  // 异步恢复光标位置（下一帧）
  requestAnimationFrame(() => {
    try {
      inputEl.setSelectionRange(start, end);
    } catch {}
  });
}

function rulesFor(i) {
  const x = layers[i];

  // ✅ 如果是创建系统层，不校验 deptId
  if (creatingSystem.value && x?.nodeType === "SYSTEM") {
    const { deptId, ...rest } = rules;
    return rest;
  }

  // ✅ 如果当前层是“子设备”（MODULE），也不校验 deptId
  if (x?.nodeType === "MODULE") {
    const { deptId, ...rest } = rules;
    return rest;
  }

  // 其他情况使用默认规则
  return rules;
}


const rules = reactive({
  nodeType: [{ required: true, message: "请选择类型", trigger: "change" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入编号", trigger: "blur" }],
  deptId: [
    { required: true, message: "请选择归属部门", trigger: ["change", "blur"] },
  ],
});

// 类型自动推进
// function nextType(prev) {
//   if (prev === "MACHINE") return "MODULE";
//   return "MODULE";
// }

// function nextType(prev) {
//   const idx = ORDER.indexOf(prev);
//   if (idx < 0) return "PART";
//   return ORDER[Math.min(idx + 1, ORDER.length - 1)];
// }

// 路径预览
function pathPreview(i) {
  const parts = [];
  for (let k = 0; k <= i; k++) {
    const r = layers[k];
    if (!r?.name) continue;
    parts.push(r.code ? `${r.name}(${r.code})` : r.name);
  }
  return parts.join(" / ");
}

// 卡片操作
function addTail() {
  if (layers.length === 0) {
    if (creatingSystem.value) {
      return ElMessage.warning("创建系统模式下不支持新增下一层。");
    } else {
      if (!selectedParentId.value)
        return ElMessage.error("请先选择起始父节点。");
      const nextTypeMap = {
        SYSTEM: "MACHINE",
        MACHINE: "MODULE",
        MODULE: "COMPONENT",
        COMPONENT: "PART",
      };
      const firstType = nextTypeMap[selectedParentType.value] || "MACHINE";
      layers.push(makeEmptyLayer(firstType));
    }
    return;
  }

  // ✅ 新增：防止超过“子设备”层级
  const last = layers[layers.length - 1];
  // if (last.nodeType === "MODULE") {
  //   return ElMessage.warning("已达到最大层级（子设备），无法再新增下一层。");
  // }

  if (creatingSystem.value) {
    return ElMessage.warning("创建系统模式下不支持新增下一层。");
  }

  layers.push(makeEmptyLayer(nextType(last.nodeType)));
}

// function addTail() {
//   if (layers.length === 0) {
//     if (creatingSystem.value) {
//       return ElMessage.warning("创建系统模式下不支持新增下一层。");
//     } else {
//       if (!selectedParentId.value)
//         return ElMessage.error("请先选择起始父节点。");
//       const nextTypeMap = {
//         SYSTEM: "MACHINE",
//         MACHINE: "MODULE",
//         MODULE: "COMPONENT",
//         COMPONENT: "PART",
//       };
//       const firstType = nextTypeMap[selectedParentType.value] || "MACHINE";
//       layers.push(makeEmptyLayer(firstType));
//     }
//     return;
//   }
//   if (creatingSystem.value) {
//     return ElMessage.warning("创建系统模式下不支持新增下一层。");
//   }
//   const last = layers[layers.length - 1];
//   layers.push(makeEmptyLayer(nextType(last.nodeType)));
// }

function insertAfter(i) {
  if (creatingSystem.value) return;
  const src = layers[i];
  layers.splice(i + 1, 0, makeEmptyLayer(nextType(src.nodeType)));
}
function dup(i) {
  if (creatingSystem.value) return;
  const src = layers[i];
  layers.splice(i + 1, 0, {
    ...JSON.parse(JSON.stringify(src)),
    uid: Math.random().toString(36).slice(2),
  });
}
function remove(i) {
  if (creatingSystem.value) return;

  if (layers.length > 1) {
    layers.splice(i, 1);

    // ✅ 若删完只剩一层且该层不是母设备，则自动重置为母设备
    if (layers.length === 1 && layers[0].nodeType !== "MACHINE") {
      layers[0].nodeType = "MACHINE";
    }
  }
}

function moveUp(i) {
  if (i > 0) {
    const t = layers[i - 1];
    layers[i - 1] = layers[i];
    layers[i] = t;
  }
}
function moveDown(i) {
  if (i < layers.length - 1) {
    const t = layers[i + 1];
    layers[i + 1] = layers[i];
    layers[i] = t;
  }
}

// 统一切换入口（不再有“切回系统”的toggle）
function switchMode(newMode) {
  mode.value = newMode;

  // 每次切换都清场
  rootPath.value = [];
  hideAllCards();
  refreshCascader();

  if (newMode === "system") {
    creatingSystem.value = true;
    showAllNodes.value = false;
    parentLabel.value = "系统";
    layers.splice(0, layers.length, makeEmptyLayer("SYSTEM"));
  } else if (newMode === "device") {
    creatingSystem.value = false;
    showAllNodes.value = false; // 只选系统
    parentLabel.value = "系统";

    // ✅ 这里添加这一段：默认打开一个母设备卡片
    if (layers.length === 0) {
      layers.push(makeEmptyLayer("MACHINE"));
    }
  } else if (newMode === "anyDevice") {
    creatingSystem.value = false;
    showAllNodes.value = true; // 强制任意节点
    parentLabel.value = "自定义设备层级节点";
  }
}

 

// 打开弹窗（两种模式）

// 打开弹窗：默认进入“创建母设备（系统）”选择
function openDialog(asCreateSystem) {
  visible.value = true;

  // ✅ 默认直接进入“创建母设备”模式
  mode.value = "device";
  creatingSystem.value = false;
  showAllNodes.value = false;
  parentLabel.value = "系统";
  rootPath.value = [];
  hideAllCards();
  refreshCascader();

  // ✅ 自动创建并显示一个母设备卡片
  if (layers.length === 0) {
    layers.push(makeEmptyLayer("MACHINE"));
  }

  // ✅ 如果传参为 true，则表示“创建系统”，保持原逻辑
  if (asCreateSystem) {
    creatingSystem.value = true;
    rootPath.value = [];
    layers.splice(0, layers.length, makeEmptyLayer("SYSTEM")); // ✅ 重新创建，仅系统卡片
  }
}

// 重置
function resetDialog() {
  rootPath.value = [];
  layers.splice(0, layers.length);
}

// 选择变更：只保留第一段（系统层）
// 选择父节点后再生成卡片
async function onRootChange(val) {
  if (!Array.isArray(val) || val.length === 0) {
    rootPath.value = [];
    hideAllCards();
    return;
  }

  // ❌ 删除这一段
  // if (mode.value === "device") {
  //   if (val.length > 1) {
  //     rootPath.value = [val[0]];
  //     ElMessage.warning("起始父节点仅支持选择系统层，已自动纠正为系统。");
  //   }
  // }

  const nodes = cascaderRef.value?.getCheckedNodes?.() || [];
  const node = nodes[0]?.data || {};
  const parentType = node.nodeType || node.node_type || "SYSTEM";

  const nextTypeMap = {
    SYSTEM: "MACHINE",
    MACHINE: "MODULE",
    MODULE: "COMPONENT",
    COMPONENT: "PART",
    PART: "PART",
  };
  const nextType = nextTypeMap[parentType] || "MACHINE";

  layers.splice(0, layers.length, makeEmptyLayer(nextType));
}

function onTypeChange(i) {
  // 可选：当第 i 层类型变化时，自动把 i+1..末尾 的类型顺着链条重算
  for (let k = i + 1; k < layers.length; k++) {
    layers[k].nodeType = nextType(layers[k - 1].nodeType);
  }
}

// 滚动到第一个校验错误（可选增强）
function scrollToFirstError(formRef) {
  const el =
    formRef?.$el?.querySelector?.(".is-error") ||
    document.querySelector(".el-form-item.is-error");
  el?.scrollIntoView?.({ behavior: "smooth", block: "center" });
}

// 逐层校验所有表单
async function validateAllLayers() {
  for (let i = 0; i < formRefs.length; i++) {
    const f = formRefs[i];
    if (!f) continue;
    try {
      await f.validate();
    } catch (e) {
      scrollToFirstError(f);
      throw e; // 立刻中止提交
    }
  }
}

// 提交
const emit = defineEmits(["refresh"]);
async function submit() {
  // 先做 Element Plus 的表单校验（包含 deptId 必填）
  try {
    await validateAllLayers();
  } catch {
    return; // 有错误就不往下走，表单上会有红色提示
  }

  if (creatingSystem.value) {
    if (layers.length !== 1 || layers[0].nodeType !== "SYSTEM") {
      return ElMessage.error("创建系统模式仅支持创建单层系统。");
    }
  } else {
    // if (!selectedParentId.value) {
    //   return ElMessage.error("请先选择起始父节点。");
    // }
    // ✅ 若在创建母设备模式下，没有选择系统节点，需要判断是否填写系统信息
    if (!creatingSystem.value && mode.value === "device") {
      const hasParentSystem = selectedParentId.value && selectedParentId.value !== 0;
      const hasManualSystemInfo =  systemInfo.code?.trim() && systemInfo.name?.trim();

      if (!hasParentSystem && !hasManualSystemInfo) {
        return ElMessage.error("请先选择系统节点或填写系统信息后再提交。");
      }
    }
  }
  if (!layers.length) return ElMessage.error("请至少新增一层");

  for (let i = 0; i < layers.length; i++) {
    const x = layers[i];
    if (!x.nodeType || !x.name)
      return ElMessage.error(`第 ${i + 1} 层：类型、名称为必填`);
  }

  const startParentId = creatingSystem.value ? 0 : selectedParentId.value;
  // 在 submit() 里加：先校验每一层的 deptId 是否为叶子
  for (let i = 0; i < layers.length; i++) {
    const x = layers[i];
    if (x.deptId && !isLeafDeptId(x.deptId)) {
      return ElMessage.error(
        `第 ${i + 1} 层的“归属部门”必须选择具体部门（不能选目录/公司层）`
      );
    }
  }

  let systemInfoData = {
      code: systemInfo.code || null,
      name: systemInfo.name || null,
      isKey: systemInfo.isKey ?? 0,
  };

  const payload = {
    startParentId,
    reuseCode: false, 
    systemInfo:systemInfoData,
    layers: layers.map((it) => ({
      nodeType: it.nodeType,
      name: it.name,
      code: it.code, 
      spareIds: it.spareIds || [],
      spareRelations: it.spareRelations
        .filter((sr) => sr.spareId)
        .map((sr) => ({
          spareId: sr.spareId,
          vendor: sr.vendor,
          spec: sr.spec,
        })),      
      spareCustom: it.spareCustom || [],
      remark: it.remark,
      specification: it.specification,
      model: it.model,
      material: it.material,
      power: it.power,
      brand: it.brand,
      manufacturer: it.manufacturer,
      isSpecial: it.isSpecial,
      deptId: it.deptId,
      status: it.status,

      // 新增字段
      mokuai: it.mokuai ?? null,
      area: it.area ?? null,
      designTemp: it.designTemp ?? null,
      designPress: it.designPress ?? null,
      motorPower: it.motorPower ?? null,
      mixingType: it.mixingType ?? null,
      beType: it.beType ?? null,
      unit: it.unit ?? null,
      quantity: it.quantity ?? null,
      amount: it.amount ?? null,
    })),
  };

  loading.value = true;
  try {
    const res = await createRoute(payload);
    if (res.code === 200) {
      if (creatingSystem.value) {
        console.log(res);

        const newId = Array.isArray(res.ids) ? res.ids[0] : res.id;
        // 选中新系统并切到“创建母设备”模式（若你想继续引导创建链路）
        mode.value = "device";
        creatingSystem.value = false;
        rootPath.value = [newId]; // ← “并把级联默认选中刚创建的系统”
        await nextTick();
        onRootChange(rootPath.value); // 生成第一张“母设备”卡
        return;

        // ✅ 创建系统成功：不关闭弹窗，刷新并聚焦父节点选择框
        ElMessage.success("系统创建成功");
        refreshCascader(); // 触发级联懒加载，拿到最新系统
        hideAllCards();
        creatingSystem.value = false; // 退出“创建系统”模式，便于选择父节点后走母设备流程
        await focusCascader(); // 鼠标焦点放到选择框
        return; // 不关闭弹窗
      }

      // ✅ 其他情况按原逻辑：关闭弹窗（如在已有系统下建链）
      ElMessage.success("新增成功");
      refreshCascader(); // 若你也想在建链成功后刷新下拉，保留这行
      emit("refresh", startParentId);
      visible.value = false;
    } else {
      ElMessage.error(res?.msg || "新增失败");
    }
  } catch (e) {
    // ElMessage.error(e?.msg || "创建失败");
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.inline {
  display: inline-block;
}
.mb12 {
  margin-bottom: 12px;
}
.ml12 {
  margin-left: 12px;
}
.mt8 {
  margin-top: 8px;
}
.flex-row {
  display: flex;
  align-items: center;
}
.tip {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

.cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.layer-card {
  border-radius: 12px;
}
.card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-head .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}
.sep {
  color: #c0c4cc;
}
.path-preview {
  color: #909399;
}

.layer-form :deep(.el-input),
.layer-form :deep(.el-select),
.layer-form :deep(.el-input-number) {
  width: 100%;
}

.add-area {
  margin-top: 10px;
}

.cas-opt {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}
.cas-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.cas-badge {
  flex: 0 0 auto;
}

/* 备件表格样式 */
.spare-table-header,
.spare-table-row {
  display: grid;
  grid-template-columns: 30% 30% 30% 10%;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 6px 10px;
}

.spare-table-header {
  background: #f5f7fa;
  font-weight: 500;
  color: #606266;
  border-top: 1px solid #ebeef5;
}

.spare-table-row {
  background: #fff;
}
.spare-table-row:nth-child(even) {
  background: #fafafa;
}

.col {
  padding: 4px 8px;
}

.col-ops {
  text-align: center;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.add-spare-btn {
  margin-top: 8px;
  text-align: right;
  margin-bottom: 10px;
}

/* ✅ 新增：滚动容器（只滚表体，保留表头吸顶） */
.spare-scroll {
  max-height: 45vh;
  overflow: auto;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background: #fff;
  /* 让“行”的上下留白不被裁掉 */
  padding: 0 6px 6px;
}

/* ✅ 让表头在容器里吸顶 */
.spare-table-header {
  position: sticky;
  top: 0;
  z-index: 1;
}

/* 保持你原有的网格列布局不变 */
.spare-table-header,
.spare-table-row {
  display: grid;
  grid-template-columns: 30% 30% 30% 10%;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 6px 10px;
}

.spare-table-header {
  background: #f5f7fa;
  font-weight: 500;
  color: #606266;
  border-top: 1px solid #ebeef5;
}

/* 让对话框整体按列布局，并限制高度 */
:deep(.dlg-fixed-footer .el-dialog) {
  display: flex;
  flex-direction: column;
  height: 80vh; /* 对话框总高度 */
  max-height: 90vh; /* 防止过高溢出屏幕 */
}

/* 头部加一条底边更清晰，可选 */
:deep(.dlg-fixed-footer .el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f2f5;
}

/* 主体区域占满剩余空间并可滚动 */
:deep(.dlg-fixed-footer .el-dialog__body) {
  flex: 1;
  overflow: auto; /* ★ 只有 body 滚动 */
  padding: 16px 24px; /* 你可以按需调整内边距 */
}

/* 页脚固定在底部，保持可见 */
:deep(.dlg-fixed-footer .el-dialog__footer) {
  position: sticky; /* 关键：粘在滚动容器底部 */
  bottom: 0;
  background: #fff;
  border-top: 1px solid #f0f2f5;
  padding: 12px 24px;
  z-index: 2; /* 盖住 body 内容的滚动 */
}

/* 细节：当内容很多时，底部加点阴影做层次感（可选） */
:deep(.dlg-fixed-footer .el-dialog__footer)::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: -8px;
  height: 8px;
  box-shadow: 0 -6px 12px rgba(0, 0, 0, 0.04);
  pointer-events: none;
}
</style>
